#!/usr/bin/env python
# encoding: utf-8

import sys
import urllib2
import simplejson as json
import logging
import common

request = urllib2.Request('http://picasaweb.google.com/lh/nameTagPaging',
                          headers={'Cookie': common.Cookie()})

def FetchCluster(cluster):
  return urllib2.urlopen(request,
                         "cmax=1&fmax=0&clusterid=%d&numsgs=10" % cluster).read()

def GetFacesUrls():
  result = {}
  
  for cluster_type in xrange(6):
    errors = 0
    for index in xrange(sys.maxint):
      cluster_id = cluster_type * 1000000 + index;
      try:
        logging.info("Fetching cluster %d" % cluster_id)
        reply = json.loads(FetchCluster(cluster_id).replace("while(1);", ""))
        if u"clusters" not in reply or not reply[u"clusters"]:
          raise Exception("totalclusters == 0")
      except:
        logging.info("Fetch error or cluster %d is empty" % cluster_id)
        errors += 1
        if errors > 5: break
        continue
      
      for cluster in reply[u"clusters"]:
        if u"faces" in cluster:
          for face in cluster[u"faces"]:
            photo_id = int(face[u"photoid"], 16)
            mini_photo_url = face[u"url"]
            result[photo_id] = mini_photo_url
  return result

def main():
  print GetFacesUrls()
        
if __name__ == '__main__':
  main()

